import random
import re
import time
from datetime import datetime, timedelta
from flask import render_template, jsonify, request
from app import db
from app.models.models import RechargeCard, User
from app.views.admin import admin_blu
from app.utils.common.common import login_user_data


@admin_blu.route("/admin")
@admin_blu.route("/admin/index")
@login_user_data
def index():
    return render_template("admin/index.html")


@admin_blu.route('/top')
def top():
    return render_template("admin/top.html")


@admin_blu.route('/menu')
def menu():
    return render_template("admin/menu.html")


@admin_blu.route('/bar')
def bar():
    return render_template('admin/bar.html')


@admin_blu.route('/main')
def main():
    return render_template('admin/main.html')


@admin_blu.route("/admin_list")
def admin_list():
    """ 所有生成，未使用的vip编码 """
    page = request.args.get("page",1)
    """测试开始"""
    a = db.session.query(RechargeCard.create_time).first()
    # print(a)
    # now = datetime.now()
    # print(now - a)
    """测试结束"""
    re = db.session.query(RechargeCard).order_by(RechargeCard.create_time.desc()).paginate(int(page), 10, False)
    # print(re)
    return render_template('admin/admin_list.html', rechargeCards = re.items, paginate=re)


@admin_blu.route("/production", methods=["POST"])
def production():
    print(request.form, "------------------------->")  # 前端传递到后端的数据
    time_ = request.form.get("time")
    num = request.form.get("num")
    if not all([num, time_]):
        ret = {"code": 2, "msg": "缺少参数"}
        return jsonify(ret)
    if not time_.isdigit:
        ret = {"code": 2, "msg": "时间必须为整数，单位为天"}
        return jsonify(ret)
    else:
        if time_.startswith("0"):
            ret = {"code": 2, "msg": "创建vip充值码的数量不能为0以及0开头的数字"}
            return jsonify(ret)
        time_ = int(time_)

    if not num.isdigit():
        ret = {"code": 2, "msg": "生成的数量只能为整数(纯数字)"}
        return jsonify(ret)
    else:
        if num.startswith("0"):
            ret = {"code": 2, "msg": "生成的数量只能为整数(纯数字)"}
            return jsonify(ret)
        num = int(num)

    print(time_, type(time_),num, type(num))
    letter = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
              "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
    for i in range(num):
        recharge_card = ""
        for k in range(12):
            letter_num = random.randint(0, 35)
            # print(letter_num)
            letter_str = letter[letter_num]
            up_or_low = random.randint(1, 3)
            if up_or_low == 1:
                letter_str = letter_str.upper()
            recharge_card += letter_str
        exist_ = db.session.query(RechargeCard).filter(RechargeCard.code_num == recharge_card).first()
        if not exist_:
            now = datetime.now()
            rechargeCard = RechargeCard()
            rechargeCard.code_num = recharge_card
            rechargeCard.create_time = now.strftime("%Y-%m-%d %H:%M:%S")
            rechargeCard.user_time = (now + timedelta(time_)).strftime("%Y-%m-%d")
            db.session.add(rechargeCard)
            db.session.commit()
    # # time.sleep(0.5)
    ret = {"code":0, "msg":"生成成功"}
    return jsonify(ret)


@admin_blu.route("/revise_password")
def revise_password():
    return render_template('admin/revise_password.html')


@admin_blu.route("/user_list", methods=["POST", "GET"])
def user_list():
    if request.method == "GET":
        print(request.args)
        page = request.args.get("page", 1)
        if request.args.get("find"):
            # users = db.session.query(User).filter(User.nick_name.like('%'+ request.args.get("find") +'%')).all()
            users2 = db.session.query(User).filter(User.nick_name.like('%'+ request.args.get("find") +'%')).paginate(int(page), 2, False)
            # print("模糊查询", users)
            return render_template("admin/user_list.html", users=users2.items, paginate=users2, find=request.args.get("find"))

        # users = db.session.query(User).all()
        users2 = db.session.query(User).paginate(int(page),2,False)
        print(users2, "测试-------------->")
        return render_template("admin/user_list.html", users=users2.items, paginate=users2, find=0)
    elif request.method == "POST":
        # print(request.json)
        # print(request.form)
        find = request.form.get("find", None)
        if not find:
            ret = {"code":2, "msg":"请输入你要查询的昵称"}
            return jsonify(ret)
        ret = {"code":0, "msg":find}
        return jsonify(ret)


@admin_blu.route("/add_user", methods=["POST", "GET"])
def add_user():
    if request.method == "GET":
        return render_template("admin/add_user.html")
    elif request.method == "POST":
        print(request.form)
        nick_name =request.form.get("nick_name")
        password = request.form.get("password")
        phone = request.form.get("phone")
        print(1)
        if not all([nick_name, password, phone]):
            ret = {"code": 2, "msg": "缺少参数"}
            return jsonify(ret)
        mobile = re.match(r"^1[35678]\d{9}$", phone)
        print(2)
        if not mobile:
            ret = {"code": 2, "msg": "手机号输入错误"}
            return jsonify(ret)
        used = db.session.query(User).filter(User.mobile == phone).first()
        print(3)
        if used:
            ret = {"code": 2, "msg": "该手机号已注册"}
            return jsonify(ret)
        print(4)
        if 6>len(password) or len(password)>20:
            ret = {"code": 2, "msg": "密码请输入6-20位之间"}
            return jsonify(ret)
        new_user = User()
        new_user.nick_name = nick_name
        new_user.mobile = phone
        new_user.password_hash = password
        db.session.add(new_user)
        db.session.commit()
        ret = {"code": 0, "msg": "操作成功"}
        return jsonify(ret)


@admin_blu.route("/user_rank")
def user_rank():
    return render_template("admin/user_rank.html")


@admin_blu.route("/user_message")
def user_message():
    return render_template("admin/user_message.html")


@admin_blu.route("/basic_settings")
def basic_settings():
    return render_template("admin/basic_settings.html")


@admin_blu.route("/advertising_list")
def advertising_list():
    return render_template("admin/advertising_list.html")


@admin_blu.route("/advertising")
def advertising():
    return render_template("admin/advertising.html")


@admin_blu.route("/edit_user")
def edit_user():
    return render_template("admin/edit_user.html")


@admin_blu.route("/account")
def account():
    return render_template("admin/account.html")